//
//  SetPassworldViewController.m
//  Application
//
//  Created by 薛小刚 on 2017/12/21.
//  Copyright © 2017年 薛小刚. All rights reserved.
//

#import "SetPassworldViewController.h"
#import "NSString+DES.h"
//#import "UMessage.h"

@interface SetPassworldViewController ()
/// 关闭按钮的点击事件
- (IBAction)closeButtonClicked:(id)sender;
/// 验证码的view
@property (weak, nonatomic) IBOutlet UIView *codeView;
/// 验证码的输入框
@property (weak, nonatomic) IBOutlet UITextField *codeInputView;
/// 获取验证码码的按钮
@property (weak, nonatomic) IBOutlet UIButton *getCodeButton;
/// 获取验证码的点击事件
- (IBAction)getCodeButtonClicked:(id)sender;
/// 密码的view
@property (weak, nonatomic) IBOutlet UIView *phoneView;
/// 密码的输入框
@property (weak, nonatomic) IBOutlet UITextField *inputPhoneTextfiled;
/// 登录按钮的点击事件
- (IBAction)loginButtonClicked:(id)sender;
/// 忘记密码的点击事件
- (IBAction)forgetButtonClicked:(id)sender;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;
@property (weak, nonatomic) IBOutlet UIImageView *backgroundImageView;

@end

@implementation SetPassworldViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    isAnimation = NO;
    [self setUI];
    [self getImage];
    [self.view sendSubviewToBack:self.backgroundImageView];
}
- (void)getImage {
    [NetworkingManager getNetworkRequestWithUrlString:@"http://39.106.113.252/bgmimg.json" parameters:nil isCache:NO succeed:^(id data) {
        [self.backgroundImageView sd_setImageWithURL:[NSURL URLWithString:data[@"img"]]];
    } fail:^(NSError *error) {
        self.backgroundImageView.backgroundColor = [UIColor blackColor];
    }];
}


static bool isAnimation;
- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:isAnimation];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}

- (void) viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}

/**
 设置UI
 */
- (void) setUI {
//    self.phoneView.layer.masksToBounds          = YES;
//    self.phoneView.layer.cornerRadius           = 4;
//    self.phoneView.layer.borderColor            = xgLineColor.CGColor;
//    self.phoneView.layer.borderWidth            = 1;
//
//    self.getCodeButton.layer.masksToBounds      = YES;
//    self.getCodeButton.layer.cornerRadius       = 4;
//    self.getCodeButton.layer.borderColor        = xgRedColor.CGColor;
//    self.getCodeButton.layer.borderWidth        = 1;
    
//    self.codeView.layer.masksToBounds           = YES;
//    self.codeView.layer.cornerRadius            = 4;
//    self.codeView.layer.borderColor             = xgLineColor.CGColor;
//    self.codeView.layer.borderWidth             = 1;
    
//    [self.loginButton setTitleColor:xgTextGlodColor forState:UIControlStateNormal];
    //    self.loginButton.backgroundColor = xgBackBlackColor;
    
    [self.codeInputView setValue:UIColorFromRGB(0xafafaf) forKeyPath:@"_placeholderLabel.textColor"];
    [self.inputPhoneTextfiled setValue:UIColorFromRGB(0xafafaf) forKeyPath:@"_placeholderLabel.textColor"];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void) touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (IBAction)closeButtonClicked:(id)sender {
    [self.view endEditing:YES];
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)getCodeButtonClicked:(id)sender {
    [self.view endEditing:YES];
//    [NetworkManger getNetworkRequestWithUrlString:[NSString stringWithFormat:@"/health/inter/login/mobelSendMessage"] parameters:@{@"str": [NSString getEncypt:@{@"LiZhenyangMobilePhone": [[NSUserDefaults standardUserDefaults] objectForKey:PHONE_NUMBER], @"LiZhenyangCode":@"178180"}]} isCache:NO succeed:^(id data) {
//        if ([data[@"code"] intValue] == 10015) {
//            [KeyWindow makeToast:@"验证码获取成功,请注意查收!"];
//            [self timeFire];
//        } else {
//            [KeyWindow makeToast:data[@"message"]];
//        }
//    } fail:^(NSError *error) {
//
//    }];
}
- (IBAction)loginButtonClicked:(id)sender {
    [self.view endEditing:YES];
    if (ISNULL(self.codeInputView.text)) {
        [KeyWindow makeToast:@"请输入验证码"];
        return;
    }
    if (ISNULL(self.inputPhoneTextfiled.text)) {
        [KeyWindow makeToast:@"请输入密码"];
        return;
    }
//    [NetworkManger getNetworkRequestWithUrlString:@"/health/inter/login/forgetPassword" parameters:@{@"str": [NSString getEncypt:@{@"XxwyzValidateCode":self.codeInputView.text, @"XxwyzMobile":[[NSUserDefaults standardUserDefaults] objectForKey:PHONE_NUMBER],                                                                                                                         @"XxwyzPassword" : [self.inputPhoneTextfiled.text MD5], @"XxwyzCode":@"158178"}]} isCache:NO succeed:^(id data) {
//        HXLog(@"设置密码成功了%@", data);
//        if ([data[@"code"] intValue] == 10025) {
//            
//            [NetworkManger getNetworkRequestWithUrlString:@"/health/inter/login/loginTwo" parameters:@{@"str":[NSString getEncypt:@{@"XxwyzMobile":[[NSUserDefaults standardUserDefaults] objectForKey:PHONE_NUMBER],                                                                                                                         @"XxwyzPassword" : [self.inputPhoneTextfiled.text MD5], @"XxwyzCode":@"158178"}]} isCache:NO succeed:^(id data) {
//                HXLog(@"登录成功%@", data);
//                if ([data[@"code"] intValue] == 10000) {
//                    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%@", data[@"values"][@"id"]] forKey:USERID];
//                    [[NSUserDefaults standardUserDefaults] synchronize];
//                    [UMessage addAlias: [[NSUserDefaults standardUserDefaults] objectForKey:USERID] type:kUMessageAliasTypeQQ response:^(id responseObject, NSError *error) {
//                        HXLog(@"失败信息是      %@", error);
//                    }];
//                    [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshUserMessage" object:nil];
//                    [self.navigationController.viewControllers.firstObject dismissViewControllerAnimated:YES completion:nil];
//                } else {
//                    [KeyWindow makeToast:data[@"message"]];
//                }
//            } fail:^(NSError *error) {
//                HXLog(@"登录失败%@", error);
//            }];
//        } else {
//            [KeyWindow makeToast:data[@"message"]];
//        }
//        
//    } fail:^(NSError *error) {
//        HXLog(@"设置密码失败了%@", error)
//    }];
//    
//                                                                                              
//                                                                                            
//                                                                                          
//    
    
}


/**
 倒计时
 */
- (void) timeFire {
    //验证码获取时间倒计时
    __block int timeout = 59; //倒计时时间
    //优先级
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout <= 0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 （倒计时结束后调用）
                [_getCodeButton setTitle:@"验证码" forState:UIControlStateNormal];
                //设置不可点击
                _getCodeButton.userInteractionEnabled = YES;
                //                _getCodeBtn.backgroundColor = [UIColor clearColor];
                
            });
        }else{
            //
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                NSLog(@"____%@",strTime);
                [_getCodeButton setTitle:[NSString stringWithFormat:@"%@秒",strTime] forState:UIControlStateNormal];
                //设置不可点击
                _getCodeButton.userInteractionEnabled = NO;
                //                _getCodeBtn.backgroundColor = [UIColor clearColor];
            });
            timeout--;
        }
    });
    
    dispatch_resume(_timer);
    
}

- (void)dealloc {
    [[SDImageCache sharedImageCache] clearDiskOnCompletion:nil];
    [[SDImageCache sharedImageCache] clearMemory];
}



@end
